package lm.concurrency.day7;

import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;
@Slf4j
public class ForkJoinTest {

    @Test
    public void test() {
        ForkJoinPool pool = new ForkJoinPool(4);
        //stem.out.println(pool.invoke(new MyTask(5)));
        System.out.println(pool.invoke(new addTask(1,5)));
    }

    // 1~n 之间整数的和

    class MyTask extends RecursiveTask<Integer> {

        private int n;

        public MyTask(int n) {
            this.n = n;
        }

        @Override
        public String toString() {
            return "{" + n + '}';
        }

        @Override
        protected Integer compute() {
            // 如果 n 已经为 1，可以求得结果了
            if (n == 1) {
                log.debug("join() {}", n);
                return n;
            }

            // 将任务进行拆分(fork)
            MyTask t1 = new MyTask(n - 1);

            t1.fork();
            log.debug("fork() {} + {}", n, t1);
            // 合并(join)结果
            int result = n + t1.join();
            log.debug("join() {} + {} = {}", n, t1, result);
            return result;
        }
    }


    class addTask extends RecursiveTask<Integer> {

        private int begin;
        private int end;

        public addTask(int begin,int end) {
            this.begin = begin;
            this.end = end;
        }

        @Override
        public String toString() {
            return "{" + begin + "},{"+ end + "}";
        }

        @Override
        protected Integer compute() {
            if (begin == end) {
                log.debug("compute() {} + {}", begin, end);
                return begin;
            }
            if (end-begin == 1) {
                log.debug("compute() {} + {}", begin, end);
                return end+begin;
            }
            int mid = begin + end/2;
            // 将任务进行拆分(fork)
            addTask t1 = new addTask(begin , mid);
            t1.fork();
            addTask t2 = new addTask(mid+1,end);
            t2.fork();
            log.debug("fork() {} + {}", t1, t2);
            // 合并(join)结果
            int result = t1.join()+t2.join();
            log.debug("join() {} + {} = {}", t1, t2, result);
            return result;
        }
    }
}


